package com.example.administrator.social.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.social.activitys.NewFriendsActivity;
import com.example.administrator.social.R;
import com.example.administrator.social.activitys.UserInfoActivity;
import com.example.administrator.social.adapter.ContactAdapter;
import com.example.administrator.social.model.ApplyInfo;
import com.example.administrator.social.model.Contact;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.example.administrator.social.util.request.CustomRequest;
import com.example.administrator.social.view.indexbar.IndexBar;
import com.example.administrator.social.view.indexbar.suspension.SuspensionDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMChatService;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactFragment extends Fragment {

    private static final String TAG = "zxt";
    private static final int UPDATE_ADAPTER = 0;
    private static final  int DECOTATION_TITLE_COLOR = 0xfff4f4f4;
    private RecyclerView mRecyclerView;
    private TextView mTvSideBarHint;
    /** 右侧边栏导航区域 */
    private IndexBar mIndexBar;
    /** 显示指示器DialogText*/

    private Context mContext;
    private ContactAdapter mAdapter;
    LinearLayoutManager mLinearLayoutManager;
    List<Contact> mDatas = null;
    String mUserName = "";
    Map<String,String> mStringMap = new HashMap<>();
    RequestQueue mRequestQueue;
    SuspensionDecoration decoration;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_ADAPTER:
                    updateData();
                    break;
            }
        }
    };

    public ContactFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        mContext = getContext();
        mUserName = AllenUtils.getUserName(mContext);
        mRequestQueue = Volley.newRequestQueue(mContext);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.contact_recycler_view);
        mTvSideBarHint = (TextView) view.findViewById(R.id.contact_tv_side_hint);//HintTextView
        mIndexBar = (IndexBar) view.findViewById(R.id.contact_index_bar);//IndexBar
        //监听消息
        EMClient.getInstance().chatManager().addMessageListener(listener);
        mDatas = new ArrayList<>();
        initRecyclerView();

        return view;
    }

    /**
     * 初始化右侧导航
     */
    private void initIndexBar() {
        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(mLinearLayoutManager);//设置RecyclerView的LayoutManager

        //indexbar初始化完成后,最后调用
        mIndexBar.setmSourceDatas(mDatas).invalidate();//设置数据
    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        //Recycler 字母分组标签
        decoration  = new  SuspensionDecoration(mContext, mDatas);
        decoration.setmTitleHeight(80);
        decoration.setTitleFontSize(44);
        decoration.setColorTitleBg(DECOTATION_TITLE_COLOR);
        mRecyclerView.addItemDecoration(decoration);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        //设置适配器
        mAdapter = new ContactAdapter(mContext, mDatas);
        mAdapter.setCallback(mCallback);
        mRecyclerView.setAdapter(mAdapter);
        //如果add两个，那么按照先后顺序，依次渲染。
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
    }

    /**
     * Contact RecyclerView Item OnClickListener
     * itemOnClick : content item click
     * topItemOnClick: new friends or char group
     */
    private  ContactAdapter.ContactCallback mCallback = new ContactAdapter.ContactCallback() {
        @Override
        public void itemOnClick(View view, int position) {
            Contact contact = mDatas.get(position);
            Intent intent = new Intent(mContext,UserInfoActivity.class);
            intent.putExtra("contact",contact);
            startActivity(intent);
        }
        @Override
        public void topItemOnClick(View view, int position) {
            startActivity(new Intent(mContext,NewFriendsActivity.class));
        }
    };

    /**
     * 更新数据源
     * @param
     */
    public void updateData() {
        mAdapter.setDatas(mDatas);
        initIndexBar();//设置数据
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        getUnReadFriendAddRequest();
        //发送请求获取数据
        doRequestGetContact();
        mRecyclerView.addItemDecoration(decoration);
    }

    @Override
    public void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(listener);
    }
    /**
     * 获取用户的联系人添加申请记录
     */
    public void getUnReadFriendAddRequest() {
        String url = HttpUtils.HTTP_URL +"getAddFriendsRecordUnReadCount";
        //获取用户被添加记录、也就是其他用户的申请记录
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equals("102")){
                    //Toast.makeText(mContext,R.string.network_error,Toast.LENGTH_SHORT).show();
                    System.out.println("No Data");
                    return;
                }else{
                    int count = Integer.valueOf(response.trim());
                    mAdapter.setUnReadCount(count);
                    mHandler.sendEmptyMessage(UPDATE_ADAPTER);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mAdapter.setUnReadCount(0);
                mHandler.sendEmptyMessage(UPDATE_ADAPTER);
            }
        });
        mStringMap.clear();
        mStringMap.put("name",mUserName);
        request.setParamsMap(mStringMap);
        mRequestQueue.add(request);
    }

    /**
     * 发送请求获取所有联系人
     */
    private void doRequestGetContact() {
        String url = HttpUtils.HTTP_URL+"getAllFriends";
        Map<String,String> map = new HashMap<>();
        map.put("name",mUserName);
        HttpUtils.postTextImageFile(mContext, url, map, null, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                String resultJson = response.body().string();
                if(!resultJson.trim().equals("101")){
                    mDatas = new Gson().fromJson(resultJson,new TypeToken<List<Contact>>(){}.getType());
                    //更新适配器
                    mHandler.sendEmptyMessage(UPDATE_ADAPTER);
                }
            }
        });
    }

    private EMMessageListener listener = new EMMessageListener() {
        /**
         * 以下方法监听消息
         * @param
         */
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            for (EMMessage msg : messages) {
                EMCmdMessageBody cmdBody = (EMCmdMessageBody) msg.getBody();
                //添加好友请求
                if (cmdBody.action().equals("add_request")) {
                    Log.d("caodaoxin", "cmdBody.action(); = " + cmdBody.action());
                    Log.d("caodaoxin", "who = " + msg.getTo());
                    //发送请求，从服务器获取未读的申请记录，然后进行适配器刷新
                    getUnReadFriendAddRequest();
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息.
            for (EMMessage msg : messages) {
                EMCmdMessageBody cmdBody = (EMCmdMessageBody) msg.getBody();
                //添加好友请求
                if (cmdBody.action().equals("add_request")) {
                    //发送请求，从服务器获取未读的申请记录，然后进行适配器刷新
                    getUnReadFriendAddRequest();
                }
            }
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };
}
